package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// 示例回调函数
func printCallback(timer *Timer) error {
	log.Printf("Timer %s (%s) executed at %v", timer.ID, timer.Name, time.Now())
	return nil
}

func emailCallback(timer *Timer) error {
	log.Printf("Sending email notification for timer %s (%s)", timer.ID, timer.Name)
	// 这里可以添加实际的邮件发送逻辑
	return nil
}

func backupCallback(timer *Timer) error {
	log.Printf("Starting backup task for timer %s (%s)", timer.ID, timer.Name)
	// 这里可以添加实际的备份逻辑
	return nil
}

func main() {
	// Redis 连接配置
	redisURL := "redis://localhost:6379" + "?client_cache=0"
	serviceID := "test-service"
	instanceID := "instance-1"

	// 创建分布式定时器
	dt, err := NewDistributedTimer(redisURL, serviceID, instanceID)
	if err != nil {
		log.Fatalf("Failed to create distributed timer: %v", err)
	}

	// 注册回调函数
	dt.RegisterCallback("print", printCallback)
	dt.RegisterCallback("email", emailCallback)
	dt.RegisterCallback("backup", backupCallback)

	// 启动分布式定时器
	err = dt.Start()
	if err != nil {
		log.Fatalf("Failed to start distributed timer: %v", err)
	}

	// 创建一些定时器
	timer1, err := dt.CreateTimer("daily_report", 10, "print")
	if err != nil {
		log.Printf("Failed to create timer1: %v", err)
	} else {
		log.Printf("Created timer1: %s", timer1.ID)
	}

	timer2, err := dt.CreateTimer("email_notification", 15, "email")
	if err != nil {
		log.Printf("Failed to create timer2: %v", err)
	} else {
		log.Printf("Created timer2: %s", timer2.ID)
	}

	timer3, err := dt.CreateTimer("backup_task", 20, "backup")
	if err != nil {
		log.Printf("Failed to create timer3: %v", err)
	} else {
		log.Printf("Created timer3: %s", timer3.ID)
	}

	// 打印实例信息
	log.Printf("Instance ID: %s", dt.serviceInstance.ID)
	log.Printf("Service: %s", dt.serviceInstance.Service)
	log.Printf("Host: %s:%d", dt.serviceInstance.Host, dt.serviceInstance.Port)

	// 等待中断信号
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// 定期打印状态信息
	go func() {
		ticker := time.NewTicker(30 * time.Second)
		defer ticker.Stop()

		for {
			select {
			case <-ticker.C:
				// 打印实例的定时器
				timers, err := dt.GetInstanceTimers()
				if err != nil {
					log.Printf("Failed to get instance timers: %v", err)
					continue
				}
				log.Printf("Instance %s has %d timers", dt.serviceInstance.ID, len(timers))

				// 打印服务实例
				instances, err := dt.GetServiceInstances()
				if err != nil {
					log.Printf("Failed to get service instances: %v", err)
					continue
				}
				log.Printf("Service %s has %d instances", dt.serviceInstance.Service, len(instances))
				for _, inst := range instances {
					log.Printf("  Instance %s: %s:%d (last seen: %v)",
						inst.ID, inst.Host, inst.Port, inst.LastSeen)
				}
			case <-dt.ctx.Done():
				return
			}
		}
	}()

	log.Println("Distributed timer is running. Press Ctrl+C to stop.")
	<-sigChan

	log.Println("Shutting down...")
	err = dt.Stop()
	if err != nil {
		log.Printf("Error stopping distributed timer: %v", err)
	}

	fmt.Println("Distributed timer stopped.")
}
